/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Ucop/Net/TcpRunnable.h"


namespace Ucop {
namespace Net {

    TcpRunnable::TcpRunnable(void)
        : _Mybase(NULL)
        , _MydummyEvent(NULL)
        , _Myload(0)
        , _Mythread(this)
        , _MystartEvent()
        , _Myrunning(false)
    {

    }

    TcpRunnable::~TcpRunnable(void)
    {
        _Uninitialize();
    }

    bool TcpRunnable::Start(void)
    {
        do
        {
            /* Create event base */
            _Mybase = event_base_new();
            if (!_Mybase) {
                break;
            }

            /* Create dummy event */
            _MydummyEvent = event_new(_Mybase, -1, EV_TIMEOUT | EV_PERSIST,
                &TcpRunnable::_OnTimeout, this);
            if (!_MydummyEvent) {
                break;
            }
            struct timeval tv = { 1, 0 };
            if (0 != event_add(_MydummyEvent, &tv)) {
                break;
            }

            /* Start thread */
            if (_Mythread.Start()) {
                _MystartEvent.Wait();
                return true;
            }
        } while (false);

        return false;
    }

    void TcpRunnable::Stop(void)
    {
        event_base_loopbreak(_Mybase);
    }

    void TcpRunnable::Join(void)
    {
        _Mythread.Join();
    }

    void TcpRunnable::Run(void)
    {
        _MystartEvent.Set();
        _Myrunning = true;
        event_base_dispatch(_Mybase);
        _Myrunning = false;
    }

    void TcpRunnable::_Uninitialize(void)
    {
        if (_Myrunning) {
            _Myrunning = false;

            Stop();
            Join();
        }

        if (_MydummyEvent != NULL) {
            event_free(_MydummyEvent);
            _MydummyEvent = NULL;
        }
        if (_Mybase != NULL) {
            event_base_free(_Mybase);
            _Mybase = NULL;
        }
    }

    void TcpRunnable::_OnTimeout(evutil_socket_t, short, void *)
    {

    }
}}